<template>
    <n-scrollbar x-scrollable style="max-height: 100vh">
        <CommonPage show-footer>
          <div>
            <form>
              <div style="display: flex;margin-top: -30px; align-items: center;">
                <n-form-item>
                  <label style="width:80px;">出库仓库：</label>
                  <n-select placeholder="选择仓库"
                            style="width: 180px"
                            v-model:value="searchCondition.outStoreId"
                            :options="outStores"
                  ></n-select>
                </n-form-item>
                <n-form-item style="margin-left: 10px">
                  <span style="width: 80px">入库仓库：</span>
                  <n-select style="width: 180px"
                            placeholder="选择仓库"
                            v-model:value="searchCondition.inStoreId"
                            :options="inStores"
                  ></n-select>
                </n-form-item>
                <n-form-item style="margin-left: 10px">
                  <span style="width: 70px">负责人：</span>
                  <n-select placeholder=""
                            style="width: 180px"
                            v-model:value="searchCondition.adminId"
                            :options="admins"
                  ></n-select>
                </n-form-item>
                <n-form-item style="margin-left: 10px">
                  <span style="width: 80px">调拨货品：</span>
                  <n-select v-model:value="searchCondition.transferCommodityId"
                            style="width: 180px"
                            :options="commodities">

                  </n-select>
                </n-form-item>
                <n-form-item style="margin-left: 10px">
                  <n-button type="primary"
                            @click="searchByCondition"
                            >筛选</n-button>
                </n-form-item>

              </div>
              <div style="display: flex;margin-top: -30px; align-items: center;">
                <n-form-item >
                  <n-button type="primary"
                            @click="showForm=true"
                  >
                    添加调拨单
                  </n-button>
                </n-form-item >
                <n-form-item style="margin-left: 10px">
                  <n-button type="error" @click="deleteSelectStoreTransfer">
                    批量删除
                  </n-button>
                </n-form-item>
                <n-form-item style="margin-left: 10px">
                  <n-button type="primary" @click="exportListInfo">导出</n-button>
                </n-form-item>
              </div>
              <AddTransferForm
                  :option="option"
                  @update-page="searchByCondition"
                  :show="showForm"
                  :onClose="handleClose" />
              <UpdateTransferForm
                  :option="option"
                  @update-page="searchByCondition"
                  :show1="showForm1"
                  :onClose="handleClose"
                  :storeTransfer="currentStoreTransfer"
              />
            <n-data-table
                remote
                :single-line="false"
                ref="table"
                :columns="columns"
                :data="storeTransferDocumentList"
                :loading="loading"
                :pagination="paginationReactive"
                :row-key="rowKey"
                :scroll-x="900"
                @update:checked-row-keys="handleCheck"
            />
            </form>
          </div>
        </CommonPage>
    </n-scrollbar>
</template>

<script setup>
import {onMounted, reactive, ref,h} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {formatDate} from "@/utils";
import {NTag} from 'naive-ui'
import InventoryActions from "@/views/admin/category/components/category-actions.vue";
import AddTransferForm from '@/views/admin/inventory/components/transfer-add.vue';
import UpdateTransferForm from "@/views/admin/inventory/components/transfer-edit.vue"

const currentStoreTransfer=ref(null);
const showForm=ref(false)
const showForm1=ref(false)
const handleClose = () => {
  showForm.value=false;
  showForm1.value=false;
};
const checkedRowKeysRef = ref([]);
const handleCheck =(rowKeys)=>{
  checkedRowKeysRef.value = rowKeys;
}
const time = ref(null)
const outStores=ref([{
  label:'全部',
  value:-1,
}])
const inStores=ref([{
  label:'全部',
  value:-1,
}])
const admins=ref([{
  label:'全部',
  value:-1,
}])
const commodities=ref([{
  label:'全部',
  value:-1,
}])
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const range = ref(null)
const id=userStore.getId()
const searchCondition=ref({
  outStoreId:'',
  transferCommodityId:'',
  quantity:'',
  inStoreId:'',
  adminId:'',
})
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    key: 'colId',
    title: '序号',
    width: 60,
  },
    {
        key: 'id',
        title: '编号',
        width: 60,
    },
    {
        key: 'outStoreName',
        title: '出库仓库',
        width: 100,

    },

    {
        key: 'transferCommodityName',
        title: '调拨货品',
        width: 100,
    },
    {
        key: 'quantity',
        title: '调拨数量',
        width: 100,
    },
  {
    key: 'inStoreName',
    title: '入库仓库',
    width: 100,

  },
    {
        key: 'adminName',
        title: '调拨负责人',
        width: 100,
    },

    {
        key: 'createTime',
        title: '创建时间',
        width: 100,
    },
  {
    key: 'do',
    title: '操作',
    width: 120,
    render(row) {
      return h(
        InventoryActions,
        {
          onClickEdit: () => onDetailTransfer(row),
          onClickDelete: () => onDeleteTransfer(row),
        }
      );
    }
  },
]
let total = 0
const paginationReactive = reactive({
    page: 1,
    pageSize: 50,
    showSizePicker: true,
    pageSizes: [50, 100, 150],
    itemCount:0,
    prefix: () => {
        return '查询出 ' + total + '条记录';
    },
    onChange: (page) => {
        paginationReactive.page = page;
        queryByPage()
    },
    onUpdatePageSize: (pageSize) => {
        paginationReactive.pageSize = pageSize;
        paginationReactive.page = 1;
        queryByPage()
    }
});
const searchByCondition = async ()=>{
  loading.value = true
  try {
    paginationReactive.page = 1;
    const res = await api.findPageStoreTransfer({
      params: {
        outStoreId:searchCondition.value.outStoreId,
        inStoreId:searchCondition.value.inStoreId,
        adminId:searchCondition.value.adminId,
        transferCommodityId: searchCondition.value.transferCommodityId,
        pageNum: paginationReactive.page,
        pageSize: paginationReactive.pageSize,
      }
    })
    if(res.code === 200) {
      total = res.data.total
      paginationReactive.itemCount = total
      const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
      storeTransferDocumentList.value = res.data.records.map((item,i)=>{
        return {...item,
          colId: baseCount + i + 1,
        }
      })
      $message.success("获取仓库成功！")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("查询仓库失败！")
  }finally{
    loading.value = false
  }
}
const onDeleteTransfer = async (log)=>{
    $dialog.confirm({
        title: '警告',
        content: '您确定删除当前调拨单？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            const {id} = log
            loading.value = true
            try {
                const res = await api.deleteStoreTransfer({id})
                if(res.code === 200) {
                    $message.success("删除调拨单成功！")
                    // await queryByPage()
                    await searchByCondition()
                }
                else {
                    $message.error(res.message)
                }
            } catch (err) {
                $message.error("删除调拨单失败！")
            }finally{
                loading.value = false
            }
        }
    })
}
const onDetailTransfer = async (storeTransfer)=>{
    const {id} = storeTransfer
  showForm1.value=true;
  currentStoreTransfer.value = storeTransfer;
}
const storeTransferDocumentList=ref([])
const queryByPage = async ()=>{
    loading.value = true
    try {
        const res = await api.findPageStoreTransfer(
          {
            params: {
              pageNum: paginationReactive.page,
              pageSize: paginationReactive.pageSize,
            }
          })
        if(res.code === 200) {
            total = res.data.total
            paginationReactive.itemCount = total
          storeTransferDocumentList.value = res.data.records.map((item,i)=>{
                return {...item,
                    colId: i+1
                }
            })
            $message.success("获取调拨单成功！")
        }
        else {
            $message.error(res.message)
        }
    } catch (err) {
        $message.error("获取调拨单失败！")
    }finally{
        loading.value = false
    }
}
const deleteSelectStoreTransfer = ()=>{
  console.log(checkedRowKeysRef.value)
  if(checkedRowKeysRef.value.length <= 0) {
    $message.error("当前并未选择调拨单！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选调拨单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      console.log(ids)
      loading.value = true
      try {
        const res = await api.deleteStoreTransfers({ params: { ids } })
        if(res.code === 200) {
          $message.success("删除所选调拨单成功！")
          // await queryByPage()
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选调拨单失败！")
      }finally{
        loading.value = false
      }
    },
  })
}
const exportListInfo = async () => {
  const res = await api.exportStoreTransferList({
    outStoreId: searchCondition.value.outStoreId,
    transferCommodityId: searchCondition.value.transferCommodityId,
    quantity:searchCondition.value.quantity,
    inStoreId: searchCondition.value.inStoreId,
    adminId:searchCondition.value.adminId,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if(contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
  if(window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else{
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.download= fileName;
    elink.style.display ="none"
    elink.href  = window.URL.createObjectURL(blob)
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const queryStoreList = async () => {
  loading.value = true
  try {
    const res = await api.findAllStore()
    if(res.code === 200) {
      res.data.map((item)=>{
        outStores.value.push({
          label: item.name,
          value: item.id
        })
        inStores.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库信息失败！")
  }finally{
    loading.value = false
  }
}
const queryStoreCommodityList = async () => {
  loading.value = true
  try {
    const res = await api.findAllInventory()
    if(res.code === 200) {
      res.data.map((item)=>{
        commodities.value.push({
          label: item.productName,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库信息失败！")
  }finally{
    loading.value = false
  }
}
const queryAdminList = async () => {
  loading.value = true
  try {
    const res = await api.findAdminByRole({
      role: 'STOREADMIN'
    })
    if(res.code === 200) {
      res.data.map((item)=>{
        admins.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取管理员信息失败！")
  }finally{
    loading.value = false
  }
}

  const rowKey = (rowData) => {
      return rowData.id
  }
  onMounted(()=>{
      queryByPage()
    queryStoreList()
    queryAdminList()
    queryStoreCommodityList()
  })
</script>
<style scoped>
    :deep(.n-data-table-th__title),
    :deep(.n-data-table-td) {
        text-align: center;

    }
    :deep(.n-select) {
        width: 140px !important;
    }

    :deep(.two-line-description) {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2; /* 控制显示的行数 */
        overflow: hidden;
    }

</style>
